package org.jash.common.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.GridLayoutManager.SpanSizeLookup
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.Adapter
import androidx.recyclerview.widget.RecyclerView.ViewHolder

class CommonAdapter<D>(val map:(d:D) -> Pair<Int,Int>, val data:MutableList<D> = mutableListOf(), val span:(d:D) -> Int = {_ -> 1}) : Adapter<CommonViewHolder>() {
    private var listener:((d:D) -> Unit)? = null;
    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        super.onAttachedToRecyclerView(recyclerView)
        val manager = recyclerView.layoutManager
        if (manager is GridLayoutManager) {
            manager.spanSizeLookup = object :SpanSizeLookup() {
                override fun getSpanSize(position: Int): Int = span(data[position])
            }
        }
    }
    override fun getItemViewType(position: Int): Int {
        return map(data[position]).first
    }
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CommonViewHolder =
        CommonViewHolder(DataBindingUtil.inflate<ViewDataBinding?>(LayoutInflater.from(parent.context), viewType, parent, false))
    override fun getItemCount(): Int = data.size

    override fun onBindViewHolder(holder: CommonViewHolder, position: Int) {
        var d = data[position]
        listener?.let { l ->
            holder.binding.root.setOnClickListener {
                l(d)
            }
        }
        holder.binding.setVariable(map(d).second, d)
    }
    operator fun plusAssign(list:List<D>) {
        val size = data.size
        data.addAll(list)
        notifyItemRangeInserted(size, list.size)
    }
    fun setOnItemClickListener(l:(d:D) -> Unit) {
        listener = l;
    }
    operator fun minusAssign(d:D) {
        val position = data.indexOf(d)
        data.remove(d)
        notifyItemRemoved(position)
    }
}
class CommonViewHolder(val binding:ViewDataBinding):ViewHolder(binding.root)